import axios from 'axios'

// 创建axios实例
const instance = axios.create({
  baseURL: 'https://api.example.com', // API基础路径
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么，比如添加token
    // config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    return config
  },
  error => {
    // 处理请求错误
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response.data
  },
  error => {
    // 根据错误码做些事情，比如401则跳转到登录页
    if (error.response && error.response.status === 401) {
      // 清除token并跳转到登录页
      // localStorage.removeItem('token');
      // window.location.href = '/login';
    }
    return Promise.reject(error)
  }
)

// 封装GET方法
const get = (url = '', params = {}) => {
  return new Promise((resolve, reject) => {
    instance.get(url, { params })
      .then(resolve)
      .catch(reject)
  })
}

// 封装POST方法
const post = (url = '', data = {}) => {
  return new Promise((resolve, reject) => {
    instance.post(url, data)
      .then(resolve)
      .catch(reject)
  })
}

// 封装文件下载方法
const download = (url = '', params = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'GET',
      params,
      responseType: 'blob' // 重要：设置响应类型为blob
    }).then(response => {
      const blob = new Blob([response.data], { type: 'application/octet-stream' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = 'filename.extension' // 更改这里的文件名和扩展名
      link.click()
      resolve()
    }).catch(reject)
  })
}

// 封装文件上传方法
const upload = (url = '', formData = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: progressEvent => {
        // 进度条处理
        console.log(`Uploaded ${progressEvent.loaded} bytes out of ${progressEvent.total}`)
      }
    }).then(resolve).catch(reject)
  })
}

// 导出封装的方法
export { get, post, download, upload }
